package org.jeecg.modules.demo.publicplace.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.demo.base.service.IZnzfEmployeeService;
import org.jeecg.modules.demo.projectroom.service.IZnzfRoomService;
import org.jeecg.modules.demo.publicplace.entity.ZnzfMyPublicApplyAndStateParam;
import org.jeecg.modules.demo.publicplace.entity.ZnzfMyPublicApplyParam;
import org.jeecg.modules.demo.publicplace.entity.ZnzfPublicApply;
import org.jeecg.modules.demo.publicplace.entity.ZnzfPublicOpen;

import org.jeecg.modules.demo.publicplace.service.IZnzfPublicApplyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.publicplace.service.IZnzfPublicOpenService;
import org.jeecg.modules.demo.publicplace.service.IZnzfPublicService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 公共场所预约
 * @Author: jeecg-boot
 * @Date:   2022-04-11
 * @Version: V1.0
 */
@Api(tags="公共场所预约")
@RestController
@RequestMapping("/publicplace/znzfPublicApply")
@Slf4j
public class ZnzfPublicApplyController extends JeecgController<ZnzfPublicApply, IZnzfPublicApplyService> {
	@Autowired
	private IZnzfPublicApplyService znzfPublicApplyService;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private IZnzfEmployeeService znzfEmployeeService;

	@Autowired
    private IZnzfPublicOpenService znzfPublicOpenService;

	@Autowired
	private ISysAnnouncementService sysAnnouncementService;

	@Autowired
    private IZnzfRoomService znzfRoomService;

	@Autowired
    private IZnzfPublicService znzfPublicService;

	/**
	 * 分页列表查询
	 *
	 * @param znzfPublicApply
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "公共场所预约-分页列表查询")
	@ApiOperation(value="公共场所预约-分页列表查询", notes="公共场所预约-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ZnzfPublicApply>> queryPageList(ZnzfPublicApply znzfPublicApply,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZnzfPublicApply> queryWrapper = QueryGenerator.initQueryWrapper(znzfPublicApply, req.getParameterMap());
		Page<ZnzfPublicApply> page = new Page<ZnzfPublicApply>(pageNo, pageSize);
		IPage<ZnzfPublicApply> pageList = znzfPublicApplyService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param znzfPublicApply
	 * @return
	 */
	@AutoLog(value = "公共场所预约-添加")
	@ApiOperation(value="公共场所预约-添加", notes="公共场所预约-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ZnzfPublicApply znzfPublicApply) {
		znzfPublicApplyService.save(znzfPublicApply);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param znzfPublicApply
	 * @return
	 */
	@AutoLog(value = "公共场所预约-编辑")
	@ApiOperation(value="公共场所预约-编辑", notes="公共场所预约-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ZnzfPublicApply znzfPublicApply) {
		znzfPublicApplyService.updateById(znzfPublicApply);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公共场所预约-通过id删除")
	@ApiOperation(value="公共场所预约-通过id删除", notes="公共场所预约-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		znzfPublicApplyService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "公共场所预约-批量删除")
	@ApiOperation(value="公共场所预约-批量删除", notes="公共场所预约-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.znzfPublicApplyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "公共场所预约-通过id查询")
	@ApiOperation(value="公共场所预约-通过id查询", notes="公共场所预约-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ZnzfPublicApply> queryById(@RequestParam(name="id",required=true) String id) {
		ZnzfPublicApply znzfPublicApply = znzfPublicApplyService.getById(id);
		if(znzfPublicApply==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(znzfPublicApply);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param znzfPublicApply
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZnzfPublicApply znzfPublicApply) {
        return super.exportXls(request, znzfPublicApply, ZnzfPublicApply.class, "公共场所预约");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZnzfPublicApply.class);
    }

	 /**
	  * 用户预约
	  * @param request request
	  * @param publicOpenId 预约时间段id
	  * @param applyNum 预约人数
	  * @return
	  */
	 //@AutoLog(value = "公共场所预约-用户预约")
	 @ApiOperation(value="公共场所预约-用户预约", notes="公共场所预约-用户预约")
	 @GetMapping(value = "/userReservation")
	 public Result userReservation(HttpServletRequest request,
                                   @RequestParam(name="publicOpenId",required=true) String publicOpenId,
                                   @RequestParam(name="applyNum",required=true) String applyNum) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 String uid = sysUserService.getUserByName(name).getId();
		 // 根据uid查找eid
         String eid = znzfEmployeeService.findEidByUid(uid);

         // 通过znzfPublicOpen的主键找到一条对应的记录
		 ZnzfPublicOpen znzfPublicOpen = znzfPublicOpenService.queryZnzfPublicOpenById(publicOpenId);
         if (znzfPublicOpen == null) {
             return Result.error("未找到对应数据",null);
         }
         Date start = znzfPublicOpen.getStart();
         Date end = znzfPublicOpen.getEnd();
         // 判断用户所选的预约时间段是否已过期（不能预约当天当时之前的时间段）
         if (new Date().after(start)) {
             return Result.error("您所选的预约时间已过期，预约失败",null);
         }
         // 判断用户的预约人数是否超过最大限制
         int maxApply = znzfPublicOpen.getMaxApply();
         int applyNumber = Integer.valueOf(applyNum);
         if (applyNumber > maxApply) {
             return Result.error("此公共场所时间段限制单次最大预约人数为"+maxApply+"人，预约失败",null);
         }
         // 判断预约人数+此时间段已预约人数是否小于最大预约人数
         int currApply = znzfPublicOpen.getCurrApply();
         int contain = znzfPublicOpen.getContain();
         if ((currApply+applyNumber) > contain) {
             int currMaxNum = contain - currApply;
             return Result.error("当前时间段已预约"+currApply+"人，最大预约"+currMaxNum+"人，预约失败",null);
         }
         // 预约成功 预约表中插入数据
         String publicId = znzfPublicOpen.getPublicId();
		 try {
			 znzfPublicApplyService.insertPublicApply(publicId, publicOpenId, eid, applyNumber);
		 } catch (Exception e) {
			 System.out.println(e);
			 return Result.error("预约失败");
		 }

         return Result.ok("预约成功");
	 }

	 /**
	  * 取消预约
	  * @param request request
	  * @param publicApplyId 预约表id
	  * @return
	  */
	 @ApiOperation(value="公共场所预约-取消预约", notes="公共场所预约-取消预约")
	 @GetMapping(value = "/cancelReservation")
	 public Result cancelReservation(HttpServletRequest request,
								   @RequestParam(name="publicApplyId",required=true) String publicApplyId) {
		 //获取uid
		 String uid = sysUserService.getUserId(request);

		 // 根据uid查找eid
		 String eid = znzfEmployeeService.findEidByUid(uid);

		 int i = znzfPublicApplyService.cancelReservation(publicApplyId);
		 if (i == 0) {
			 SysAnnouncement sysAnnouncement = new SysAnnouncement();
			 sysAnnouncement.setTitile("您的公共场所预约已取消");
			 sysAnnouncement.setMsgAbstract("预约取消通知");
			 sysAnnouncement.setMsgContent("<p>您的公共场所预约已被取消<p>");
			 sysAnnouncement.setPriority("M");
			 sysAnnouncement.setMsgCategory("1");
			 sysAnnouncement.setMsgType("USER");
			 sysAnnouncement.setSendStatus("1");
			 sysAnnouncement.setDelFlag(0 + "");
			 if (eid.isEmpty()) {
				 //eid为空，则确认此次登录的为管理员
				 String real_eid = znzfPublicApplyService.queryEidById(publicApplyId);
				 //根据eid查找uid
				 uid = znzfEmployeeService.findUidByEid(real_eid);
				 sysAnnouncement.setUserIds(uid + ",");
				 String name = JwtUtil.getUsername(request.getHeader(CommonConstant.X_ACCESS_TOKEN));
				 sysAnnouncement.setSender(name);
			 } else {
				 //eid不为空，则确认此次登录的为职工
				 sysAnnouncement.setUserIds(uid + ",");
				 sysAnnouncement.setSender("我");
			 }

			 Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
			 ca.setTime(new Date()); //设置时间为当前时间
			 sysAnnouncement.setSendTime(ca.getTime());
			 sysAnnouncement.setStartTime(ca.getTime());
			 ca.add(Calendar.DATE, 30); //日期+30天
			 Date endTime = ca.getTime(); //结果
			 sysAnnouncement.setEndTime(endTime);

			 sysAnnouncementService.saveAnnouncement(sysAnnouncement);

			 return Result.ok("预约取消成功");
		 }
		 else
			 return Result.error("预约取消失败");
	 }

	 /**
	  * 通过userId查询我的预约信息
	  *
	  * @param request
	  * @return
	  */
	 @ApiOperation(value="公共场所预约-通过userId查询我的预约信息", notes="公共场所预约-通过userId查询我的预约信息")
	 @GetMapping(value = "/queryByUserId")
	 public Result<List<ZnzfMyPublicApplyAndStateParam>> queryByUserId(HttpServletRequest request) {
		 //获取uid
		 String userId = sysUserService.getUserId(request);
		 List<ZnzfMyPublicApplyAndStateParam> list = znzfPublicApplyService.getByUserId(userId);
		 if(list==null) {
			 return Result.error("未找到对应数据",null);
		 }
		 return Result.OK(list);
	 }

}
